package com.boss.salary.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boss.common.entity.PageDTO;
import com.boss.common.service.ICommonService;
import com.boss.common.util.DateUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.IAgencySalaryPaymentDao;
import com.boss.salary.entity.AgencySalaryPayment;
import com.boss.salary.service.IAgencySalaryPaymentService;
import com.boss.sys.ca.user.dto.UserDTO;
import com.boss.sys.utils.SysUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AgencySalaryPaymentServiceImpl implements IAgencySalaryPaymentService {

    @Autowired
    private IAgencySalaryPaymentDao iAgencySalaryPaymentDao;

    @Autowired
    private ICommonService iCommonService;

    @Override
    public PageDTO<AgencySalaryPayment> queryAgencySalaryPaymentPage(PaginationDTO paginationDTO, Map<String, Object> queryParam,String tokenid) {
        List<AgencySalaryPayment> list = iAgencySalaryPaymentDao.queryAgencySalaryPaymentPage(paginationDTO, queryParam);
        if (!StringUtils.isEmpty(list) && list.size() > 0) {
            // 获取所有指标id
            List<String> bgtId = list.stream().filter(bean-> !StringUtils.isEmpty(bean.getBgtId())).collect(Collectors.toList())
                    .stream().map(AgencySalaryPayment::getBgtId).collect(Collectors.toList());
            Map<String, Object> query = new HashMap<>(1);
            if (!StringUtils.isEmpty(bgtId) && bgtId.size() > 0) {
                query.put("condition", SysUtils.inSql("sum_id", bgtId));
                query.put("mof_div_code", queryParam.get("mof_div_code"));
                query.put("fiscal_year", queryParam.get("fiscal_year"));
                query.put("offset", queryParam.get("page"));
                query.put("limit", queryParam.get("limit"));
                list = getBgtData(list, query,tokenid);
            }
        }
        int total = iAgencySalaryPaymentDao.queryAgencySalaryPaymentTotal(queryParam);
        PageDTO<AgencySalaryPayment> pageDTO = new PageDTO<>();
        pageDTO.setRows(list);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    @Override
    public PageDTO getIndexPage(Map<String, Object> queryParam,String tokenid){
        StringBuilder sql = new StringBuilder();
        sql.append(" and agency_id = '").append(queryParam.get("agencyId")).append("'");
        if (!StringUtils.isEmpty(queryParam.get("payTypeCode"))) {
            sql.append(" and pay_type_code = '").append(queryParam.get("payTypeCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("proCatCode"))) {
            sql.append(" and pro_cat_code = '").append(queryParam.get("proCatCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("proCode"))) {
            sql.append(" and c.pro_code = '").append(queryParam.get("proCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("depBgtEcoCode"))) {
            sql.append(" and dep_bgt_eco_code = '").append(queryParam.get("depBgtEcoCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("payCategoryCode"))) {
            sql.append(" and pay_category_code = '").append(queryParam.get("payCategoryCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("funcCode"))) {
            sql.append(" and exp_func_code = '").append(queryParam.get("funcCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("isSal"))) {
            sql.append(" and is_sal_code = '").append(queryParam.get("isSal")).append("'");
        }
       // sql.append(" and pay_category_code = '11'");
        queryParam.put("condition", sql.toString());
        JSONArray jsonArray = iCommonService.getPayMent(queryParam, true,tokenid);
        int total = iCommonService.getPayMentCount(queryParam, true,tokenid);
        PageDTO pageDTO = new PageDTO();
        pageDTO.setTotal(total);
        pageDTO.setRows(jsonArray);
        return pageDTO;
    }
    @Override
    public PageDTO getIndexRulePage(Map<String, Object> queryParam,List<String> agencyIds,String tokenid){
        StringBuilder sql = new StringBuilder();
        sql.append(" and ").append( SysUtils.inSql("agency_id", agencyIds));
        //sql.append(" and agency_id = '").append(queryParam.get("agencyIds")).append("'");
        if (!StringUtils.isEmpty(queryParam.get("payTypeCode"))) {
            sql.append(" and pay_type_code = '").append(queryParam.get("payTypeCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("proCatCode"))) {
            sql.append(" and pro_cat_code = '").append(queryParam.get("proCatCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("proCode"))) {
            sql.append(" and c.pro_code = '").append(queryParam.get("proCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("depBgtEcoCode"))) {
            sql.append(" and dep_bgt_eco_code = '").append(queryParam.get("depBgtEcoCode")).append("'");
        }
       if (!StringUtils.isEmpty(queryParam.get("payCategoryCode"))) {
            sql.append(" and pay_category_code = '").append(queryParam.get("payCategoryCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("funcCode"))) {
            sql.append(" and exp_func_code = '").append(queryParam.get("funcCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("govBgtEcoCode"))) {
            sql.append(" and gov_bgt_eco_code = '").append(queryParam.get("govBgtEcoCode")).append("'");
        }
        if (!StringUtils.isEmpty(queryParam.get("isSal"))) {
            sql.append(" and is_sal_code = '").append(queryParam.get("isSal")).append("'");
        }
        //sql.append(" and pay_category_code = '11'");
        queryParam.put("condition", sql.toString());
        JSONArray jsonArray = iCommonService.getPayMent(queryParam, true,tokenid);
        int total = iCommonService.getPayMentCount(queryParam, true,tokenid);
        PageDTO pageDTO = new PageDTO();
        pageDTO.setTotal(total);
        pageDTO.setRows(jsonArray);
        return pageDTO;
    }
    @Override
    public List<AgencySalaryPayment> getHookUpData(String salaryId, String personType, String year, String province, String agencyId,String tokenid) {
        List<AgencySalaryPayment> list = iAgencySalaryPaymentDao.getHookUpData(salaryId, personType, year, province, agencyId);
        if (!StringUtils.isEmpty(list) && list.size() > 0) {
            // 获取所有指标id
            List<String> bgtId = list.stream().filter(bean-> !StringUtils.isEmpty(bean.getBgtId())).collect(Collectors.toList())
                    .stream().map(AgencySalaryPayment::getBgtId).collect(Collectors.toList());
            Map<String, Object> query = new HashMap<>(1);
            if (!StringUtils.isEmpty(bgtId) && bgtId.size() > 0) {
                query.put("condition", SysUtils.inSql("sum_id", bgtId));
                query.put("mof_div_code",province);
                list = getBgtData(list, query,tokenid);
            }
        }else{

        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveHookUpData(AgencySalaryPayment agencySalaryPayment, UserDTO userDTO) {
        // 删除改工资和人员类型下的挂接数据
        iAgencySalaryPaymentDao.deleteHookUpData(agencySalaryPayment.getSalaryId(), agencySalaryPayment.getPersonType(),
                String.valueOf(userDTO.getYear()), userDTO.getProvince(), agencySalaryPayment.getAgencyId());
        // 保存新挂接的数据
        List<Map<String, Object>> bgtInfoLists = agencySalaryPayment.getBgtInfos();
        if (!StringUtils.isEmpty(bgtInfoLists) && bgtInfoLists.size() > 0) {
            List<Object[]> datas = new ArrayList<>(bgtInfoLists.size());
            for (Map<String, Object> map : bgtInfoLists) {
                String bgtId = map.get("bgtId").toString();
                String isUsing = map.get("isUsing").toString();
                String payOrder = map.get("payOrder").toString();
                Object[] objects = new Object[] {
                        SysUtils.generateGuid(), SysUtils.generateGuid(), SysUtils.generateGuid(),
                        String.valueOf(DateUtils.getCurrentTimeStamp()), String.valueOf(DateUtils.getCurrentTimeStamp()),
                        userDTO.getYear(), userDTO.getProvince(), agencySalaryPayment.getAgencyId(), agencySalaryPayment.getPersonType(),
                        agencySalaryPayment.getSalaryId(), agencySalaryPayment.getAgencySalaryId(), agencySalaryPayment.getSalaryItemizeId(),
                        bgtId, agencySalaryPayment.getColumnName(), isUsing, payOrder, SystemDictConstant.IS_FALSE,userDTO.getProvince()
                };
                datas.add(objects);
            }
            // 保存挂接信息
            iAgencySalaryPaymentDao.saveHookUpData(datas);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRuleHookUpData(AgencySalaryPayment agencySalaryPayment, UserDTO userDTO) {
        List<String> bgtIds=new ArrayList<>();
        // 保存新挂接的数据
        List<Map<String, Object>> bgtInfoLists = agencySalaryPayment.getBgtInfos();
        if (!StringUtils.isEmpty(bgtInfoLists) && bgtInfoLists.size() > 0) {
            List<Object[]> datas = new ArrayList<>(bgtInfoLists.size());
            for (Map<String, Object> map : bgtInfoLists) {
                String bgtId = map.get("bgtId").toString();
                String isUsing = map.get("isUsing").toString();
                String payOrder = map.get("payOrder").toString();
                String agencyId=map.get("agency_id").toString();//指标本身的单位id
                bgtIds.add(bgtId);
                Object[] objects = new Object[] {
                        SysUtils.generateGuid(), SysUtils.generateGuid(), SysUtils.generateGuid(),
                        String.valueOf(DateUtils.getCurrentTimeStamp()), String.valueOf(DateUtils.getCurrentTimeStamp()),
                        userDTO.getYear(), userDTO.getProvince(), agencyId, agencySalaryPayment.getPersonType(),
                        agencySalaryPayment.getSalaryId(), agencySalaryPayment.getAgencySalaryId(), agencySalaryPayment.getSalaryItemizeId(),
                        bgtId, agencySalaryPayment.getColumnName(), isUsing, payOrder, SystemDictConstant.IS_FALSE,userDTO.getProvince()
                };
                datas.add(objects);
            }
            // 删除改工资和人员类型下的挂接数据
            iAgencySalaryPaymentDao.deleteHookUpDataByBgtId(agencySalaryPayment.getSalaryId(), agencySalaryPayment.getPersonType(),
                    String.valueOf(userDTO.getYear()), userDTO.getProvince(), bgtIds);
            // 保存挂接信息
            iAgencySalaryPaymentDao.saveHookUpData(datas);
        }
    }



    /**
     * 获取指标数据
     * @return
     */
    private List<AgencySalaryPayment> getBgtData(List<AgencySalaryPayment> list, Map<String, Object> query,String tokenid) {
        // 获取所有的指标
        JSONArray jsonArray = iCommonService.getPayMent(query,false,tokenid);
        if (!StringUtils.isEmpty(jsonArray) && jsonArray.size() > 0) {
            // 根据选择的指标id，获取具体内容
            for (AgencySalaryPayment agencySalaryPayment : list) {
                if (!StringUtils.isEmpty(agencySalaryPayment.getBgtId())) {
                    // 如果有挂接的指标id，则获取指标信息
                    String bgtId = agencySalaryPayment.getBgtId();
                    if (!StringUtils.isEmpty(bgtId)) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            String sumId = jsonObject.getString("sum_id");
                            // 如果指标id相同
                            if (bgtId.equals(sumId)) {
                                // 指标文号
                                String corBgtDocNoName = jsonObject.getString("corBgtDocNoName");
                                agencySalaryPayment.setCorBgtDocNoName(corBgtDocNoName);
                                // 指标总额
                                String aviamt = jsonObject.getString("aviamt");
                                agencySalaryPayment.setAviamt(aviamt);
                                // 可用指标额
                                String canuseamt = jsonObject.getString("canuseamt");
                                agencySalaryPayment.setCanuseamt(canuseamt);
                                // 支付方式
                                String payTypeName = jsonObject.getString("payTypeName");
                                agencySalaryPayment.setPayTypeName(payTypeName);
                                // 资金性质
                                String fundTypeName = jsonObject.getString("fundTypeName");
                                agencySalaryPayment.setFundTypeName(fundTypeName);
                                // 指标id
                                agencySalaryPayment.setBgtId(bgtId);
                                // 功能分类编码
                                String expFuncCode = jsonObject.getString("expFuncCode");
                                agencySalaryPayment.setExpFuncCode(expFuncCode);
                                // 功能分类名称
                                String expFuncName = jsonObject.getString("expFuncName");
                                agencySalaryPayment.setExpFuncName(expFuncName);
                                // 项目分类
                                String proCatName = jsonObject.getString("proCatName");
                                agencySalaryPayment.setProCatName(proCatName);
                                // 预算项目
                                String proName = jsonObject.getString("proName");
                                agencySalaryPayment.setProName(proName);
                                // 经济分类编码
                                String depBgtEcoNo = jsonObject.getString("depBgtEcoNo");
                                agencySalaryPayment.setDepBgtEcoNo(depBgtEcoNo);
                                // 经济分类名称
                                String depBgtEcoName = jsonObject.getString("depBgtEcoName");
                                agencySalaryPayment.setDepBgtEcoName(depBgtEcoName);
                                break;
                            }
                        }
                    }
                }
            }
        }
        return list;
    }
    @Override
    public List<AgencySalaryPayment> getPaymentLock(String agencyId) {
        List<AgencySalaryPayment> list=iAgencySalaryPaymentDao.getPaymentLock(agencyId);
        return list;
    }
}
